package com.pinhuba.bams.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.pinhuba.bams.R;
import com.pinhuba.bams.framework.ErrorCode;
import com.pinhuba.bams.framework.UrlType;
import com.pinhuba.bams.framework.controller.Controller;
import com.pinhuba.bams.framework.controller.ErrorListener;
import com.pinhuba.bams.framework.Params;
import com.pinhuba.bams.framework.util.JsonHandle;
import com.pinhuba.bams.framework.util.Loger;
import com.pinhuba.bams.framework.util.ToastHelper;

public class AnnounceListActivity extends Activity {
	private LinearLayout announceListLayout;
	private RelativeLayout announceTitleLayout;
	private Button backBtn;
	private Button homeBtn;
	private TextView titleTv;
	private ProgressDialog progressDialog;

	private ListView listView;
	private View footerView;

	private List<HashMap<String, Object>> dataList;
	private Adapter adapter;

	private int totalRows;
	private int currentPage;
	private boolean hasMoreData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.announce_list);
		initView();
		initData();
		setListener();
	}

	@Override
	protected void onResume() {
		super.onResume();
		Loger.d("onresume");
		adapter.notifyDataSetChanged();
	}

	void initView() {
		announceListLayout = (LinearLayout) findViewById(R.id.announce_list);
		announceTitleLayout = (RelativeLayout) findViewById(R.id.toptitle);
		backBtn = (Button) announceTitleLayout.findViewById(R.id.back_btn);
		homeBtn = (Button) announceTitleLayout.findViewById(R.id.home_btn);
		titleTv = (TextView) announceTitleLayout.findViewById(R.id.title);
		progressDialog = new ProgressDialog(this);

		listView = (ListView) findViewById(R.id.notifyListView);
		footerView = View.inflate(AnnounceListActivity.this, R.layout.dataloading, null);
	}

	void initData() {
		totalRows = 0;
		currentPage = 1;
		hasMoreData = true;
		titleTv.setText(R.string.announce_list);
		listView.addFooterView(footerView, null, true);
		dataList = new ArrayList<HashMap<String, Object>>();
		adapter = new Adapter();

		listView.setAdapter(adapter);
		footerView.setVisibility(View.GONE);

		announceListLayout.setVisibility(View.INVISIBLE);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		String tempMsg = getResources().getString(R.string.getingdata) + titleTv.getText().toString() + getResources().getString(R.string.ellipsis);
		progressDialog.setMessage(tempMsg);
		progressDialog.show();
		Controller.getInstance().doRequest(AnnounceListActivity.this, UrlType.ANNOUNCE_LIST, errorListener, Params.announceList(currentPage, 0));
	}

	void setListener() {
		backBtn.setOnClickListener(toptitleListener);
		homeBtn.setOnClickListener(toptitleListener);
		listView.setOnScrollListener(scrollListener);
		listView.setOnItemClickListener(itemClickListener);
	}

	private OnClickListener toptitleListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (v == homeBtn) {
				Intent it = new Intent(AnnounceListActivity.this, MainActivity.class);
				it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(it);
			} else {
				AnnounceListActivity.this.finish();
			}
		}
	};

	private OnItemClickListener itemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> group, View view, int position, long id) {
			Intent it = new Intent(AnnounceListActivity.this, AnnounceDetailActivity.class);
			it.putExtra("id", dataList.get(position).get("primaryKey").toString());
			startActivity(it);
		}
	};

	private OnScrollListener scrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (footerView.getVisibility() == View.VISIBLE) {
				return;
			}
			if (!hasMoreData) {
				return;
			}
			if (scrollState == SCROLL_STATE_IDLE) {
				if (view.getLastVisiblePosition() == view.getCount() - 1) {
					currentPage += 1;
					Controller.getInstance().doRequest(AnnounceListActivity.this, UrlType.ANNOUNCE_LIST, errorListener, Params.announceList(currentPage, 0));
					footerView.setVisibility(View.VISIBLE);
				}
			}
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

		}
	};

	private ErrorListener errorListener = new ErrorListener() {

		@Override
		public void onSuccess(UrlType type, String json) {
			Loger.d("The json in upfile is :" + json);
			
			footerView.setVisibility(View.GONE);
			
			if (progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			if (announceListLayout.getVisibility() == View.INVISIBLE) {
				announceListLayout.setVisibility(View.VISIBLE);
			}
			JSONObject jsonObj = null;
			try {
				jsonObj = new JSONObject(json);
				if (JsonHandle.getInstance().jsonCodeHandle(jsonObj) == 0) {
					totalRows = jsonObj.getInt("totalRows");

					JSONArray jsonArray = jsonObj.getJSONArray("list");
					String[] strArray = { "primaryKey", "oaAnnoName", "oaAnnoTime"};
					dataList = JsonHandle.getInstance().jsonCodeArrayHandle(dataList, jsonArray, strArray);
					if (dataList.size() >= totalRows) {
						hasMoreData = false;
						listView.removeFooterView(footerView);
					}
				}
				adapter.notifyDataSetChanged();
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}

		@Override
		public void onError(UrlType api, ErrorCode code) {
			if (progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			switch (code) {
			case READW_TIMOUT:
				ToastHelper.showShortMsg(R.string.exception_readw_timeout);
				break;
			case AIRPLANE_MODE:
				ToastHelper.showShortMsg(R.string.exception_airplane_mode);
				break;
			case NO_INTERNET:
				ToastHelper.showShortMsg(R.string.exception_no_internet);
				break;
			case INVALID_IO:
				ToastHelper.showShortMsg(R.string.exception_invaild_io);
				break;
			default:
				break;
			}
		}
	};

	private class Adapter extends BaseAdapter {

		public int getCount() {
			if (dataList != null) {
				return dataList.size();
			}
			return 0;
		}

		@Override
		public Object getItem(int position) {
			if (dataList != null) {
				return dataList.get(position);
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			if (dataList != null) {
				return position;
			}
			return 0;
		}

		private class Holder {
			private TextView title;
			private TextView time;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Holder holder;
			if (convertView == null) {// 如果convertView为空
				holder = new Holder();
				convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.announce_list_item, null);
				holder.title = (TextView) convertView.findViewById(R.id.title);
				holder.time = (TextView) convertView.findViewById(R.id.create_time);
				convertView.setTag(holder);// 把workHolder的内容放入tag
			} else {// 如果convertView不为空，把之前为空时候放入workHolder的内容读出来
				holder = (Holder) convertView.getTag();
			}
			HashMap<String, Object> tempMap = dataList.get(position);
			holder.title.setText(tempMap.get("oaAnnoName").toString());
			holder.time.setText(tempMap.get("oaAnnoTime").toString());
			return convertView;
		}

	}
}
